package com.github.pig.nideshop.controller.user;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.ZyResult;
import com.github.pig.nideshop.entity.NideshopCart;
import com.github.pig.nideshop.entity.NideshopGoods;
import com.github.pig.nideshop.entity.NideshopProduct;
import com.github.pig.nideshop.model.dto.CartDTO;
import com.github.pig.nideshop.service.INideshopCartService;
import com.github.pig.nideshop.service.INideshopGoodsService;
import com.github.pig.nideshop.service.INideshopProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  购物车 前端控制器
 * </p>
 *
 * @author J神
 * @since 2018-06-11
 */
@RestController
@RequestMapping("/carts")
public class NideshopCartController {
    @Autowired
    private INideshopCartService nideshopCartService;
    @Autowired
    private INideshopProductService nideshopProductService;
    @Autowired
    private INideshopGoodsService nideshopGoodsService;
    /**
     * 添加到购物车
     */
    @PostMapping
    public ZyResult add(@RequestBody NideshopCart nideshopCart){
        NideshopProduct product= nideshopProductService.selectById(nideshopCart.getProductId());
        NideshopGoods nideshopGoods=nideshopGoodsService.selectById(nideshopCart.getGoodsId());
        nideshopCart.setChecked(true);
        nideshopCart.setGoodsName(nideshopGoods.getName());
        nideshopCart.setGoodsSn(nideshopGoods.getGoodsSn());
        return ZyResult.ok(nideshopCartService.insert(nideshopCart));
    }

    /**
     * 更新购物车
     * @param cartDTO
     * @return
     */
    @PutMapping
    public ZyResult update(@RequestBody CartDTO cartDTO){
        EntityWrapper entityWrapper=new EntityWrapper();
        if(cartDTO.getIds()!=null&&cartDTO.getIds().size()>0){
            entityWrapper.in("id",cartDTO.getIds());
        }
        else{
            entityWrapper.eq("id",cartDTO.getId());
        }
        return ZyResult.ok(nideshopCartService.update(cartDTO,entityWrapper));
    }

    /**
     * 移除
     * @param cartDTO
     * @return
     */
    @DeleteMapping
    public ZyResult delete(@RequestBody CartDTO cartDTO){
        if(cartDTO.getIds()!=null&&cartDTO.getIds().size()>0){
            return ZyResult.ok(nideshopCartService.deleteBatchIds(cartDTO.getIds()));
        }
        else{
            return ZyResult.ok(nideshopCartService.deleteById(cartDTO.getId()));
        }

    }

    /**
     * 购物车列表
     * @param nideshopCart
     * @param page
     * @return
     */
    @GetMapping
    public ZyResult carts(NideshopCart nideshopCart,Page page){
        return ZyResult.ok(nideshopCartService.selectList(new EntityWrapper<>(nideshopCart)));
    }
}

